package com.example.student.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.domain.pojo.Question;
import com.example.common.domain.pojo.WrongBooks;
import com.example.common.utils.CacheClient;
import com.example.student.Converter.JsonConverter;
import com.example.student.domain.Dto.WrongBooksQuery;
import com.example.student.domain.Vo.WringQuestionVo;
import com.example.student.domain.Vo.WrongBooksVo;
import com.example.student.mapper.HomeworkQuestionMapper;
import com.example.student.mapper.WrongBooksMapper;
import com.example.student.service.QuestionService;
import com.example.student.service.WrongBooksService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;


@Service
@Slf4j
public class WrongBooksServiceImpl extends ServiceImpl<WrongBooksMapper, WrongBooks> implements WrongBooksService {

    @Autowired
    private HomeworkQuestionMapper homeworkQuestionMapper;
    @Autowired
    private CacheClient cacheClient;
    @Autowired
    private QuestionService questionService;


//    @Override
//    @Transactional
//    public Page<WrongBooksVo> getWrongBooks(WrongBooksQuery query) {
//        Page<WrongBooksVo> page = new Page<>(query.getPageNum(), query.getPageSize());
//        LambdaQueryWrapper<WrongBooks> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(WrongBooks::getStudentId, query.getStudentId())
//                .eq(WrongBooks::getCourseId, query.getCourseId());
//        List<WrongBooks> wrongBooks = this.list(queryWrapper);
//        LambdaQueryWrapper<Question> queryWrapper1 = new LambdaQueryWrapper<>();
//
//    }

    @Override
    @Transactional(readOnly = true)
    public Page<WrongBooksVo> getWrongBooks(WrongBooksQuery query) {
        // 1. 查询错题列表（已完成）
        Page<WrongBooks> wrongBooksPage = this.page(
                new Page<>(query.getPageNum(), query.getPageSize()),
                new LambdaQueryWrapper<WrongBooks>()
                        .eq(WrongBooks::getStudentId, query.getStudentId())
                        .eq(WrongBooks::getCourseId, query.getCourseId())
        );
        // 2. 提取题目ID列表
        List<String> questionIds = wrongBooksPage.getRecords().stream()
                .map(WrongBooks::getQuestionId)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        // 3. 如果没有题目ID，直接返回空分页
        if (questionIds.isEmpty()) {
            return new Page<>(wrongBooksPage.getCurrent(), wrongBooksPage.getSize(), 0);
        }
        // 4. 查询题目详情并应用过滤条件
        LambdaQueryWrapper<Question> questionQuery = new LambdaQueryWrapper<>();
        questionQuery.in(Question::getId, questionIds);
        // 应用题目过滤条件
        if (StringUtils.isNotBlank(query.getQuestionType())) {
            questionQuery.eq(Question::getType, query.getQuestionType());
        }
        if (StringUtils.isNotBlank(query.getQuestionName())) {
            questionQuery.like(Question::getQuestionText, query.getQuestionName());
        }
        if (StringUtils.isNotBlank(query.getQuestionDifficulty())) {
            questionQuery.eq(Question::getDifficulty, query.getQuestionDifficulty());
        }
        if (StringUtils.isNotBlank(query.getKnowledgePoint())) {
            // 假设知识点是JSON数组存储，使用JSON_CONTAINS查询
            questionQuery.apply("JSON_CONTAINS(knowledge_points, '\"" + query.getKnowledgePoint() + "\"')");
        }

        // 5. 查询题目列表
        List<Question> questionList = questionService.list(questionQuery);
        // 6. 将题目ID映射到题目对象（用于快速查找）
        Map<String, Question> questionMap = questionList.stream()
                .collect(Collectors.toMap(Question::getId, q -> q));
        // 7. 转换错题列表为Vo，并关联题目详情
        List<WrongBooksVo> voList = wrongBooksPage.getRecords().stream()
                .filter(wrongBook -> questionMap.containsKey(wrongBook.getQuestionId()))
                .map(wrongBook -> {
                    Question question = questionMap.get(wrongBook.getQuestionId());
                    WringQuestionVo questionVo = convertToQuestionVo(question);
                    return convertToWrongBooksVo(wrongBook, questionVo);
                })
                .collect(Collectors.toList());
        // 8. 构建分页结果
        Page<WrongBooksVo> resultPage = new Page<>(wrongBooksPage.getCurrent(), wrongBooksPage.getSize(), wrongBooksPage.getTotal());
        resultPage.setRecords(voList);
        return resultPage;
    }

    // 将Question转换为WringQuestionVo
    private WringQuestionVo convertToQuestionVo(Question question) {
        WringQuestionVo vo = new WringQuestionVo();
        BeanUtils.copyProperties(question, vo);

        // 转换JSON字符串为Map/List
        vo.setOptions(JsonConverter.stringToMap(question.getOptions()));
        vo.setCorrectAnswers(JsonConverter.stringToList(question.getCorrectAnswers()));
        vo.setKnowledgePoints(JsonConverter.stringToList(question.getKnowledgePoints()));
        return vo;
    }

    // 将WrongBooks和WringQuestionVo合并为WrongBooksVo
    private WrongBooksVo convertToWrongBooksVo(WrongBooks wrongBook, WringQuestionVo questionVo) {
        WrongBooksVo vo = new WrongBooksVo();
        BeanUtils.copyProperties(wrongBook, vo);
        vo.setWringQuestionVo(questionVo);
        return vo;
    }
}
